<template>
  <ContentWrap>
    <!-- 表单 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
      :inline="true"
    >
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <div>
              <span class="title">{{ formTitle }}</span>
            </div>
            <div class="button-group">
              <el-button type="primary" @click="submitForm" :loading="formLoading">保存</el-button>
              <el-button @click="cancel">返回</el-button>
            </div>
            <div> </div>
          </div>
        </template>

<el-row :gutter="24">
<el-col :span="8">
  <el-form-item label-width="130" label="项目名称" prop="name">
          <el-input v-model="formData.name"  :maxLength="30"  placeholder="请输入项目名称" />
        </el-form-item>
</el-col >

<el-col :span="8">
     <el-form-item label-width="130"  label="项目起始日期" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>

</el-col>


<el-col :span="8">
        
        <el-form-item label-width="130" label="项目截止日期" prop="endTime">
                <el-date-picker
                  v-model="formData.endTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item>
      </el-col>


</el-row>

<el-row :gutter="24">
  <el-col :span="8">
    <el-form-item  label="合同金额（万元)" label-width="130" prop="contractAmount">
          <el-input
            v-model="formData.contractAmount"
            :maxLength="20"
            placeholder="请输入合同金额（万元)"
          />
        </el-form-item>
  </el-col>



  <el-col :span="8" >
          <el-form-item label-width="130" label="甲方单位" prop="firstpartyId">
            <el-tree-select

              v-model="formData.firstpartyId"
              :data="treeList"
              check-strictly
              :props="defaultProps"
              @node-click="handleChangeTree"
            />
          </el-form-item>
        </el-col>



        <el-col :span="8">
    <el-form-item label-width="130" label="合同编号" prop="contractNum">
          <el-input v-model="formData.contractNum"  placeholder="请输入合同编号" />
        </el-form-item>
  </el-col>


</el-row>


<el-row :gutter="24">


  <el-col :span="8">

          
<el-form-item label-width="130" label="项目管理员" prop="projectManager">
  <el-input
    v-model="formData.projectManager"
    :maxLength="10"
    placeholder="请输入项目管理员"
  />
</el-form-item>
</el-col>

  <el-col :span="8">
        
    <el-form-item label-width="130" label="承检机构" prop="orgIds">
          <!-- <el-input v-model="formData.orgIds" placeholder="请输入承检机构" /> -->
          <el-select
            v-model="formData.orgIds"
            multiple
            filterable
            placeholder="请选择承检机构"
            @change="handleSelectChange"
            :render-label="renderLabel"
            @popup-scroll="handlePopupScroll"
             ref="selectRef"
             :filter-method="handleFocus"
          >
            <el-option
              v-for="item in companyList"
              :key="item.value"
              :label="item.label"
              :value="String(item.value)"
            />
          </el-select>
        </el-form-item>
    </el-col>


    <el-col :span="8">
      <el-form-item label="第三方人员" prop="thirdpartyName">
          <!-- <el-autocomplete
            v-model="formData.thirdpartyName"
            :fetch-suggestions="querySearch"
            clearable
            :value-key="id"
            class="inline-input w-50"
            placeholder="请输入第三方人员"
            @select="handleSelect"
          >
            <template #suffix>
              <i class="iconfont icon-sousuo"></i>
            </template>
          </el-autocomplete> -->

          <el-input v-model="formData.thirdpartyName"  placeholder="请输入第三方人称">
            <template #suffix>
              <i class="iconfont icon-sousuo" style="cursor: pointer" @click="handleSearch1"></i>
            </template>
          </el-input>
        </el-form-item>
    </el-col>



</el-row>







      </el-card>

      <!-- 操作按钮 -->
    </el-form>
  </ContentWrap>

  <el-dialog v-model="dialogVisbal" width="1200" title="选择第三方人员">
    <el-form inline :model="dialogForm">
        <el-form-item label="姓名">
          <el-input v-model="dialogForm.name" placeholder="请输入姓名"/>
          </el-form-item>

          <el-form-item label="单位">
          <el-input v-model="dialogForm.companyName" placeholder="请输入单位"/>
          </el-form-item>

          <el-form-item label="登录名">
          <el-input v-model="dialogForm.loginName" placeholder="请输入登录名"/>
          </el-form-item>
          <el-form-item class="flex; justify-center;">
            <el-button type="primary" @click="onSearch">搜索</el-button>
            <el-button  @click="onReset">重置</el-button>
          </el-form-item>



<div style="max-height: 300px; overflow-y: auto">
  <el-table :data="tableData" >
      <el-table-column width="55">
        <template #header>
          <span>选择</span>
        </template>
        <template #default="scope">
          <el-radio v-model="selectedRowId" :value="scope.row.id" @change="dialogRadio1(scope.row)" />
        </template>
      </el-table-column>
<el-table-column label="单位" prop="companyName" />
<el-table-column label="姓名" prop="name" />
<el-table-column label="登录名" prop="loginName" />
<el-table-column label="用户角色" prop="roleName" />
<el-table-column label="手机" prop="phone" />
<el-table-column label="邮箱" prop="email" />



</el-table>

</div>
<div style=" display: flex;margin-top: 20px; justify-content: center;" >
  <el-button type="primary" @click="handleEntry">确定</el-button>
  <el-button @click="handleReset">取消</el-button>
</div>
      </el-form>
  </el-dialog>
 
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ProjectManagemenrApi } from '@/api/qis/projectmanagemenr'
import { useMessage } from '@/hooks/web/useMessage'
import { UserInfoApi } from '@/api/qis/userInfo'
import { OrganizationQualificationApi } from '@/api/qis/organizationqualification'

import { useUserStore } from '@/store/modules/user'
import { dealTreeAddDisable } from '@/utils/tree-date-deal'



const dialogVisbal = ref(false)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const router = useRouter() // 路由
const route = useRoute() // 当前路由

const userStore = useUserStore()
const userName = computed(() => userStore.user.nickname ?? 'Admin')

// 表单标题
const formTitle = computed(() => {
  return route.query.id ? '修改项目' : '新增项目'
})

const tableData = ref([])

const handleSearch1 = ()=>{
  dialogVisbal.value = true
}

const dialogForm = ref({})

// 搜索
const onSearch = ()=>{
  getThreeMan()
}
// 重置
const onReset = ()=>{
  dialogForm.value = {}
  getThreeMan()
}

// 确定
const handleEntry  = ()=>{
  formData.thirdpartyName = selectItem.value.name
  formData.thirdpartyId = selectItem.value.id
  onReset()
  dialogVisbal.value = false
}

// 取消
const handleReset = ()=>{
  onReset()
  dialogVisbal.value = false

}

const selectedRowId =ref(1)

const selectItem =ref({})

const dialogRadio1 = (row) =>{
  selectItem.value = row
}

const selectArr = ref([])
const handleSelectChange = (selectedValues) => {
  selectArr.value = []
  console.log(selectedValues, 'selectedValues')


 companyList.value.forEach(item=>{
    let a = ''
    selectedValues.forEach(v=>{
      if(item.value == v){
        selectArr.value.push(item.label)
      }
    })

    
  })
  formData.orgNames = selectArr.value.join(';')+';'
  console.log(selectArr.value,'selectArr')

  // selectArr.value =  companyList.value.map((item) => {
  //   console.log(item.value)
  //    selectedValues.forEach((v) => {
  //     console.log(v)
  //     if (item.value == v) {
  //       console.log(item,'item')
  //       return item.label
  //     }
  //   })
  // })

  console.log(selectArr.value,'selectArr')


}

// 表单数据

let formData = reactive({
  // firstpartyId: []
})

const handleChangeTree = (value) => {
  console.log(value, 'value')
  formData.firstpartyName = value.name
}

// 表单校验规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { max: 30, message: '项目名称的长度不能超过30个字符', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入机构地址', trigger: 'blur' }],
  legalUnit: [{ required: true, message: '请输入法人单位名称', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择项目起始日期', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择项目截止日期', trigger: 'change' }],
  contractNum: [
    { required: true, message: '请输入合同编号', trigger: 'blur' },
    { max: 30, message: '合同编号的长度不能超过30个字符', trigger: 'blur' }
    //  {
    //           validator: (rule, value, callback) => {
    //             if (!/^\d+(\.\d{1,4})?$/.test(value)) {
    //               callback(new Error('合同编号必须是数字且最多保留4位小数'));
    //             } else {
    //               callback();
    //             }
    //           },
    //           trigger: 'blur'
    //         }
  ],
  inspectionOrg: [{ required: true, message: '请输入承检机构', trigger: 'blur' }],
  firstpartyId: [{ required: true, message: '请输入甲方单位', trigger: 'change' }],
  contractAmount: [
    { required: true, message: '请输入合同金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (/^\d+(\.\d+)?$/.test(value)) {
          callback()
        } else {
          callback(new Error('合同金额必须为数字'))
        }
      },
      trigger: 'blur'
    },
    {
      max: 20,
      message: '合同金额的长度不能超过20个字符',
      trigger: 'blur'
    }
  ],
  projectManager: [
    { required: true, message: '请输入项目管理员', trigger: 'blur' },
    { max: 10, message: '项目管理员的长度不能超过10个字符', trigger: 'blur' }
  ],
  orgIds: [{ required: true, message: '请选择机构', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref
const formLoading = ref(false) // 表单的加载中

/** 获取表单数据 */
const getFormData = async (id: string) => {}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  console.log(formData.firstpartyId, 'first_party')
  await formRef.value.validate()
  formData.orgIds = Array.isArray(formData.orgIds)
    ? formData.orgIds.join(';') + ';'
    : formData.orgIds + ';'
  console.log(selectArr.value)
  console.log(formData.orgNames, 'orgNames')

  try {
    // 提交表单
    formLoading.value = true
    if (formData.id) {
      await ProjectManagemenrApi.updateProjectManagemenr(formData)
      message.success(t('common.updateSuccess'))
    } else {
      console.log(formData,'formLoading')
      await ProjectManagemenrApi.createProjectManagemenr(formData)
      message.success(t('common.createSuccess'))
    }
    formData = {}
    selectArr.value = []
    formData.orgIds = ''
    // 返回列表页
    router.push('/inspection-info-management/project-management')
  } finally {
    formLoading.value = false
  }
}

const renderLabel = (labels) => {
  return labels
    .map((label) => {
      const item = companyList.value.find((item) => item.value === label)
      return item ? item.label : label
    })
    .join(', ')
}

/** 取消按钮 */
const cancel = () => {
  router.push('/inspection-info-management/project-management')
  selectArr.value = []
  formData.orgIds = ''
}

const orgIdsOptions = [
  {
    value: 'Option1',
    label: 'Option1'
  },
  {
    value: 'Option2',
    label: 'Option2'
  }
]

const restaurants = ref([])

const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  console.log('🚀 ~ querySearch ~ results:', results, formData.thirdpartyId)
  cb(results)
}

const createFilter = (queryString: string) => {
  return (restaurant) => {
    return {
      ...restaurant,
      value: restaurant.value.toLowerCase()
    }
  }
}

const currentPage = ref(1)

const selectRef = ref()
const scrollTopSelect = ref(0)


const handlePopupScroll = (data) => {
  // console.log(data)
  scrollTopSelect.value = data.scrollTop
  // console.log(111)
  // const popper = selectRef.value.popperElm;
  // console.log(popper)
  // if (popper) {
  //   const { scrollTop, clientHeight, scrollHeight } = popper;
  //   if (scrollTop + clientHeight >= scrollHeight) {
  //     // 触底，加载下一页数据
  //     currentPage.value++;
  //     getCJJGList(currentPage.value);
  //   }
  // }
};

const handleSelect = (item) => {
  // console.log(item)
  formData.thirdpartyId = item.id
  formData.thirdpartyName = item.value
}

const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}
const treeList = ref([])
// const treeList = [
//   {
//     id: 1,
//     name: '顶级节点 1',
//     parentId: 0,
//     children: [
//       {
//         id: 11,
//         name: '一级子节点 1 - 1',
//         parentId: 1,
//         children: [
//           {
//             id: 111,
//             name: '二级子节点 1 - 1 - 1',
//             parentId: 11,
//             children: []
//           },
//           {
//             id: 112,
//             name: '二级子节点 1 - 1 - 2',
//             parentId: 11,
//             children: []
//           }
//         ]
//       },
//       {
//         id: 12,
//         name: '一级子节点 1 - 2',
//         parentId: 1,
//         children: []
//       }
//     ]
//   },
//   {
//     id: 2,
//     name: '顶级节点 2',
//     parentId: 0,
//     children: [
//       {
//         id: 21,
//         name: '一级子节点 2 - 1',
//         parentId: 2,
//         children: []
//       }
//     ]
//   },
//   {
//     id: 3,
//     name: '顶级节点 3',
//     parentId: 0,
//     children: []
//   }
// ]

const threeManList = ref([])
// 获取第三方人员
const getThreeMan = async () => {
  const data = await UserInfoApi.getUserInfoPage({
    pageNo: 1,
    pageSize: 100,
    roleCode: 'third_party',
    ...dialogForm.value
  })
  tableData.value = data.list
  console.log(data.list,'data')
  // restaurants.value = data.list.map((item) => {
  //   return { value: item.name, id: item.id }
  // })

  // formData.thirdpartyName =
  //   restaurants.value.find((item) => item.id == formData.thirdpartyId)?.value || ''
}

const companyList = ref([])
const getCJJGList = async (page) => {
  //     pageNo: page,
    // pageSize: 1000
  const data = await OrganizationQualificationApi.getOrganizationQualificationPage({

  })



//   watch(scrollTopSelect,(oldValue,newValue)=>{
//       if(oldValue<newValue + 10){
//         currentPage.value+=5
//         getCJJGList(currentPage.value)
//       }
      
// })
  companyList.value = data.list
  console.log(data)
  companyList.value = data.list.map((item: any) => {
    return {
      label: item.name,
      value: item.id
    }
  })
  // if (page === 1) {
  //     companyList.value = data.list.map((item) => {
  //       return {
  //         label: item.name,
  //         value: item.id
  //       };
  //     });
  //   } else {
  //     // 追加新数据到列表中
  //     const newData = data.list.map((item) => {
  //       return {
  //         label: item.name,
  //         value: item.id
  //       };
  //     });
  //     companyList.value = [...companyList.value, ...newData];
  //   }
  
}

// 承检机构下拉框触底

const treeRef = ref('')

const handleCheck = (data, checked, indeterminate) => {
  console.log(data, 'data')
  console.log(checked, 'checked')
  console.log(indeterminate, 'indeterminate')
  const keys = treeRef.value.getCheckedKeys()
  console.log(keys)
}

const getTreeList = async () => {
  const res = await ProjectManagemenrApi.getTreeListApi()
  treeList.value = dealTreeAddDisable(res, route.query.id)
}

const getDetail = async () => {
  const res = await ProjectManagemenrApi.getProjectManagemenr(route.query.id)
  formData = Object.assign(formData, res)
  console.log(formData,'formData')
  let arr = res.orgIds.split(';').filter((item) => item !== '')
  formData.contractNum = +res.contractNum
  formData.contractNum = res.contractNum
  formData.startTime = res.startTime
  formData.endTime = res.endTime
  formData.orgIds = arr
  console.log(res, 'res')
  formData.orgNames = res.orgNames
  // formData.thirdpartyName = restaurants.value.find(item => item.id == formData.thirdpartyId)?.value || ''
  console.log(restaurants.value, 'restaurants')
  formData.thirdpartyName = res.thirdpartyName
  
}



const handleFocus = async (value)=>{
  console.log(value,'value')
  const data = await OrganizationQualificationApi.getOrganizationQualificationPage({name:value})
  companyList.value = data.list.map((item) => {
    return {
      label: item.name,
      value: item.id
    };
  });
}

/** 初始化 */
onMounted(async () => {
  await getThreeMan()

  // 如果是修改操作，加载数据
  if (route.query.id) {
    getDetail()
  } else {
    formData.projectManager = userName.value
  }


  if(route.query.id){
    route.meta.title = '编辑项目管理'
  }else {
    route.meta.title = '新增项目管理'
  }

  getCJJGList()

  getTreeList()
})
</script>

<style lang="scss" scoped>
.title {
  font-size: 18px;
  font-weight: bold;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  justify-content: end;
  align-items: center;
  flex: 1;
}

::v-deep(.el-form--inline .el-form-item ){
  width: 100%;
}

::v-deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper){
  width: 100%;
}
</style>
